<template>
  <div class="pagination">
    <button :disabled="pageNo == 1" @click="getPageNo(pageNo - 1)">
      上一页
    </button>
    <!-- 第一页的页码什么时候才能显示 -->
    <button
      v-if="startNumAndEndNum.start > 1"
      @click="getPageNo(1)"
      :class="{ ative: pageNo == 1 }"
    >
      1
    </button>
    <!-- 省略按钮什么时候可以显示  -->
    <button v-if="startNumAndEndNum.start > 2">···</button>
    <!-- v-for不仅可以遍历数组，还可以遍历字符串，数字 -->
    <button
      v-for="(page, index) in startNumAndEndNum.end"
      :key="index"
      v-if="page >= startNumAndEndNum.start"
      @click="getPageNo(page)"
      :class="{ active: pageNo == page }"
    >
      {{ page }}
    </button>
    <!-- 省略按钮什么时候可以显示 -->
    <button v-if="startNumAndEndNum.end < totalPage - 1">···</button>
    <!-- 最后一页的页码按钮什么时候可以显示 -->
    <button
      v-if="startNumAndEndNum.end < totalPage"
      @click="getPageNo(totalPage)"
      :class="{ active: pageNo == totalPage }"
    >
      {{ totalPage }}
    </button>
    <button @click="getPageNo(pageNo + 1)">下一页</button>

    <button style="margin-left: 30px">{{ total }}</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo", "pageSize", "total", "continues"],
  computed: {
    //   计算总的页码数
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    // 计算分页器连续页码的起始位置和结束位置
    startNumAndEndNum() {
      const { continues, pageNo, totalPage } = this;
      //   不正常的情况：总页数小于连续页码数，比如总的页数只有3页，但是连续页码数是5页
      let start = 0,
        end = 0;
      if (totalPage < continues) {
        start = 1;
        end = totalPage;
      } else {
        // 正常情况
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
        // 新的不正常情况：如果当前页是第一页或者是第二页，那么start就会是-1或0;如果当前是第31页或者是第30页，那么end就会超过31，所以要再进行判断
        if (start < 1) {
          start = 1;
          end = continues;
        }
        if (end > totalPage) {
          start = totalPage - continues + 1;
          end = totalPage;
        }
      }
      return { start, end };
    },
  },
  methods: {
    getPageNo(pageNo) {
      this.$emit("getPageNo", pageNo);
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>